package com.jwds.digital.bios.business.service.rule;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 调度规则工厂
 * @author hesong
 */
@Slf4j
@Component
public class DispatchRuleSortFactory implements InitializingBean {

    private static final Map<String, DispatchRuleSortInterface> RULE_MAP = new ConcurrentHashMap<>();
    @Autowired
    private ApplicationContext context;

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            Map<String, DispatchRuleSortInterface> beansMap = context.getBeansOfType(DispatchRuleSortInterface.class);
            if (beansMap != null) {
                for (DispatchRuleSortInterface value : beansMap.values()) {
                    if (value != null && value.getRuleCode() != null) {
                        RULE_MAP.put(value.getRuleCode(), value);
                    } else {
                        log.warn("跳过无效的 DispatchRuleSortInterface 实例: {}", value);
                    }
                }
            } else {
                log.warn("未找到任何 DispatchRuleSortInterface 类型的 Bean");
            }
        } catch (BeansException e) {
            log.error("获取 DispatchRuleSortInterface 类型的 Bean 时发生错误", e);
            throw new RuntimeException(e);
        }
    }

    public DispatchRuleSortInterface getHandlerInstance(String ruleCode) {
        return RULE_MAP.get(ruleCode);
    }

    public Set<String> getRuleCodes() {
        return RULE_MAP.keySet();
    }
}
